import React, {useState, useEffect} from 'react';
import {Modal, message, Table, Button} from 'antd';
import {DndProvider} from 'react-dnd';
import {HTML5Backend} from 'react-dnd-html5-backend';
import process from 'immer';

import {getTargetPreference, deleteTarget, saveSortTarget} from '~/service/performance';
import {TARGET_TYPE} from '~/utils/const';
import DragableBodyRow from '../../component/DragableBodyRow';

const {confirm} = Modal;

const components = {
    body: {
        row: DragableBodyRow,
    },
};

/**
 * @Creator: andycao
 * @Date: 2020/05/25
 * 核心页面配置 应用内指标管理
 */
function Edit({visible, handleOk, bizId}) {
    const [list, setList] = useState();
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const columns = [
        {
            title: '序号',
            dataIndex: 'targetId',
            key: 'targetId',
            render: (val, record, index) => (index + 1)
        },
        {
            title: '路径',
            dataIndex: 'path',
            key: 'path',
            render: (text, record) => (
                <div
                    style={{
                        width: '400px',
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                    }}
                    title={text}
                >
                    {text}
                </div>
            )
        },
        {
            title: '指标',
            dataIndex: 'targetType',
            key: 'targetType',
            render: id => (
                TARGET_TYPE.get(id)
            )
        },
        {
            title: '操作',
            dataIndex: 'targetId',
            key: 'operation',
            render: id => (
                <Button size="small" onClick={remove(id)}>删除</Button>
            )
        }
    ];

    function remove(id) {
        return () => {
            confirm({
                title: '确认删除吗?',
                onOk() {
                    deleteTargetApi([id]);
                },
            });
        };
    }

    function deleteMulti() {
        confirm({
            title: '确认批量删除吗?',
            onOk() {
                if (selectedRowKeys.length > 0) {
                    deleteTargetApi(selectedRowKeys);
                }
                else {
                    message.warn('请选择删除目标');
                }
            },
        });
    }

    function deleteTargetApi(list) {
        const params = {
            bizId,
            targetIdList: list
        };
        deleteTarget(params).then(res => {
            if (res.code === 0) {
                setList(res.data.targetPreferences);
            }
            else {
                message.error(res.msg);
            }
        });
    }

    function targetListApi() {
        getTargetPreference({
            bizId
        }).then(res => {
            if (res.code === 0) {
                setList(res.data.targetPreferences);
            }
            else {
                message.error(res.msg);
            }
        });
    }

    function onSelectChange(keys) {
        setSelectedRowKeys(keys);
    }

    function closeModal() {
        setSelectedRowKeys([]);

        if (list.length === 0) {
            // close and refresh
            handleOk(true);
        }
        else {
            handleOk();
        }
    }

    // handle move event, produce new list
    function moveRow(dragIndex, hoverIndex) {
        const nextList = process(list, draft => {
            const move = draft.splice(dragIndex, 1)[0];
            draft.splice(hoverIndex, 0, move);
        });
        saveListOrder(nextList);
    }

    function saveListOrder(list) {
        const params = {
            bizId,
            targetIdList: list.map(entry => entry.targetId)
        };
        saveSortTarget(params).then(res => {
            if (res.code === 0) {
                setList(res.data.targetPreferences);
            }
            else {
                message.error(res.msg);
            }
        });
    }

    useEffect(() => {
        if (!visible) {
            return;
        }
        targetListApi();
    }, [bizId, visible]);

    return (
        <Modal
            title="应用内指标"
            visible={visible}
            onOk={closeModal}
            onCancel={closeModal}
            cancelButtonProps={{style: {display: 'none'}}}
            style={{minWidth: '60vw'}}
        >
            <p>
                按照序号顺序从左到右，从上到下排序，可拖动表格进行排序
                <Button style={{float: 'right'}} type="primary" onClick={deleteMulti}>批量删除</Button>
            </p>
            <DndProvider backend={HTML5Backend}>
                <Table
                    rowClassName="drag-sort-row"
                    rowSelection={{
                        selectedRowKeys,
                        onChange: onSelectChange,
                    }}
                    dataSource={list}
                    columns={columns}
                    rowKey="targetId"
                    pagination={false}
                    components={components}
                    // eslint-disable-next-line react/jsx-no-bind
                    onRow={(_record, index) => ({
                        index,
                        moveRow
                    })}
                />
            </DndProvider>
        </Modal>
    );
}

export default Edit;

